﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.ComponentModel;
using TestMySqlConnetPoll;
using System.Globalization;
using System.Runtime.InteropServices;

namespace View.Common
{
    
    public enum TimeFormatType
    {
        DAY,
        MONTH,
        YEAR,
        WDW,
        DCGONGLV
    }
    public class UtilityFunc
    {
        public static BindingList<HistroyAlarmObj> source = new BindingList<HistroyAlarmObj>();

        public static  bool bestfit = false;
        /// <summary>
        /// 实时报价分等级缓冲区，每种类型的报价大于1000条时，需要清除source里的数据
        /// </summary>
        public static Dictionary<string, List<HistroyAlarmObj>> sourceLevel = new Dictionary<string, List<HistroyAlarmObj>>();

        public static string BufferFormatSimple(byte[] buffer)
        {
            return UtilityFunc.BufferFormat(buffer, buffer.Length, ' ');
        }


        [DllImport("Kernel32.dll")]
        public static extern uint GetTickCount();

        private static uint preTicks = 0u;
        private static int hightTickValue = 0;

        public static long GetTickCount64()
        {
            uint tickCount = UtilityFunc.GetTickCount();
            if (tickCount < UtilityFunc.preTicks)
            {
                UtilityFunc.hightTickValue++;
            }
            UtilityFunc.preTicks = tickCount;
            return ((long)UtilityFunc.hightTickValue << 32) + (long)((ulong)tickCount);
        }

        public static string[] SplitTrimString(string str, bool bToUpper)
        {
            return UtilityFunc.SplitTrimString(str, new char[]
	        {
		        ',',
		        '，'
	        }, bToUpper, true);
        }

        public static string[] SplitTrimString(string str, char[] splitChars, bool bToUpper, bool bEmpty)
        {
            string[] result;
            if (string.IsNullOrEmpty(str))
            {
                result = null;
            }
            else
            {
                string[] array = str.Split(splitChars);
                if (array != null && array.Length > 0)
                {
                    int num = 0;
                    for (int i = 0; i < array.Length; i++)
                    {
                        array[i] = array[i].Trim();
                        if (!(array[i] == "") || !bEmpty)
                        {
                            num++;
                            if (bToUpper)
                            {
                                array[i] = array[i].ToUpper();
                            }
                        }
                    }
                    if (num > 0)
                    {
                        string[] array2 = new string[num];
                        int num2 = 0;
                        for (int i = 0; i < array.Length; i++)
                        {
                            if (!(array[i] == "") || !bEmpty)
                            {
                                if (bToUpper)
                                {
                                    array[i] = array[i].ToUpper();
                                }
                                array2[num2++] = array[i];
                            }
                        }
                        result = array2;
                        return result;
                    }
                }
                result = null;
            }
            return result;
        }

        public static string BufferFormat(byte[] buffer, int len, char spliter)
        {
            StringBuilder stringBuilder = new StringBuilder("");
            string result;
            if (buffer == null)
            {
                result = stringBuilder.ToString();
            }
            else
            {
                for (int i = 0; i < len; i++)
                {
                    stringBuilder.Append(buffer[i].ToString("X2")).Append(spliter);
                }
                result = stringBuilder.ToString();
            }
            return result;
        }

        public static string GetTimeString(DateTime time)
        {
            return time.ToString("yyyy-MM-dd HH:mm:ss");
        }

        public static void DelSourceLevel(List<ObjAlaram>dlist)
        {
            List<HistroyAlarmObj> Nlist = new List<HistroyAlarmObj>();
            foreach(ObjAlaram obj in dlist)
            {
                foreach(KeyValuePair<string,List<HistroyAlarmObj>> k in sourceLevel)
                {
                    for (int i = 0; i < k.Value.Count; i++)
                    {
                        HistroyAlarmObj x = k.Value[i];
                        if (x.alarmObj.AlarmLevel == obj.AlarmLevel && x.alarmObj.AlarmType == obj.AlarmType && x.alarmObj.dev_type == obj.dev_type
                            && x.alarmObj.dev_no == obj.dev_no && x.alarmObj.u_time == obj.u_time)
                        {
                            Nlist.Add(x);
                        }
                    }
                }
            }
            for(int i = 0;i<Nlist.Count;i++)
            {
                if(sourceLevel.ContainsKey(Nlist[i].AlarmLevel))
                {
                    try
                    {
                        sourceLevel[Nlist[i].AlarmLevel].Remove(Nlist[i]);
                    }
                    catch(Exception e)
                    {
                        Console.WriteLine("删除sourceLevel出错 " + e.ToString());
                    }
                }
                if(sourceLevel[Nlist[i].AlarmLevel].Count ==0)
                {
                    sourceLevel.Remove(Nlist[i].AlarmLevel);
                }
            }            
        }

        public static byte[] BinaryFromString(string str)
        {
            byte[] result;
            if (string.IsNullOrEmpty(str))
            {
                result = new byte[0];
            }
            else
            {
                str = str.Trim();
                int num = str.Length / 2;
                byte[] array = new byte[num + str.Length % 2];
                for (int i = 0; i < num; i++)
                {
                    array[i] = byte.Parse(str.Substring(i * 2, 2), NumberStyles.HexNumber);
                }
                if (str.Length % 2 > 0)
                {
                    array[array.Length - 1] = byte.Parse(str.Substring(str.Length - 1, 1), NumberStyles.HexNumber);
                }
                result = array;
            }
            return result;
        }

        public static string BinaryToString(byte[] buf, int maxLen)
        {
            return UtilityFunc.BinaryToString(buf, maxLen, false);
        }

        public static bool FloatIsNaN(float f)
        {
            return float.IsNaN(f) || float.IsNegativeInfinity(f) || float.IsPositiveInfinity(f);
        }

        public static string BinaryToString(byte[] buf, int maxLen, bool isShowAllInfo)
        {
            string result;
            if (buf == null)
            {
                result = "";
            }
            else
            {
                int num;
                if (isShowAllInfo)
                {
                    num = buf.Length;
                }
                else
                {
                    num = Math.Min(buf.Length, maxLen);
                }
                bool flag = num < buf.Length;
                StringBuilder stringBuilder = new StringBuilder(num * 2 + 30);
                for (int i = 0; i < num; i++)
                {
                    stringBuilder.Append(buf[i].ToString("X2") + " ");
                }
                if (flag && !isShowAllInfo)
                {
                    stringBuilder.Append(string.Format(" ... Total {0} Bytes", buf.Length));
                }
                result = stringBuilder.ToString();
            }
            return result;
        }


        public static long ToLong(string val, long defVal)
        {
            long result;
            if (string.IsNullOrEmpty(val))
            {
                result = defVal;
            }
            else
            {
                try
                {
                    if (val.StartsWith("0x") || val.StartsWith("0X"))
                    {
                        result = long.Parse(val.Substring(2, val.Length - 2), NumberStyles.HexNumber);
                    }
                    else
                    {
                        result = long.Parse(val);
                    }
                }
                catch (Exception ex)
                {
                    //DbgTrace.WriteLine(string.Format("数据转换格式错误：val: {0}  {1}", val, ex.Message));
                    result = defVal;
                }
            }
            return result;
        }

        public static float ToFloat(string val, float defVal)
        {
            float result;
            if (val == "非数字")
            {
                result = float.NaN;
            }
            else
            {
                float num = 0f;
                try
                {
                    num = Convert.ToSingle(val);
                }
                catch (Exception ex)
                {
                    //DbgTrace.WriteLine(string.Format("数据转换格式错误：val: {0}  {1}", val, ex.Message));
                    num = defVal;
                }
                result = num;
            }
            return result;
        }
        public static DateTime ToDateTime(string dateTimeStr)
        {
            DateTime result;
            try
            {
                result = DateTime.ParseExact(dateTimeStr, "yyyy-MM-dd HH:mm:ss", null);
            }
            catch
            {
                result = DateTime.MinValue;
            }
            return result;
        }

        public static int ToInt(string val, int defVal)
        {
            int result;
            if (string.IsNullOrEmpty(val))
            {
                result = defVal;
            }
            else
            {
                try
                {
                    if (!char.IsDigit(val[0]) && val[0] != '-')
                    {
                        result = defVal;
                    }
                    else
                    {
                        if (val.StartsWith("0x") || val.StartsWith("0X"))
                        {
                            result = int.Parse(val.Substring(2, val.Length - 2), NumberStyles.HexNumber);
                        }
                        else
                        {
                            result = int.Parse(val);
                        }
                    }
                }
                catch (Exception ex)
                {
                    //DbgTrace.WriteLine(string.Format("数据转换格式错误：val: {0}  {1}", val, ex.Message));
                    result = defVal;
                }
            }
            return result;
        }

        public static string GetApplicationPath()
        {
            return AppDomain.CurrentDomain.BaseDirectory;
        }

        public static string DateTimeStringFormat(DateTime dt, TimeFormatType type)
        {
            switch (type)
            {
                case TimeFormatType.DAY:
                    return dt.ToString("D");
                case TimeFormatType.MONTH:
                    return dt.ToString("y");
                case TimeFormatType.YEAR:
                    return dt.ToString("yyyy") + "年";
                case TimeFormatType.DCGONGLV:
                    return dt.ToString("G");
                case TimeFormatType.WDW:
                    return dt.ToString("G");
                default:
                    return "";
            }
        }

        public static object Clone(object obj)
        {
            MemoryStream memoryStream = new MemoryStream();
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(memoryStream, obj);
            memoryStream.Position = 0;
            return formatter.Deserialize(memoryStream);
        }
    }

    public enum UserViewLogTYPE
    {
        设备浏览记录,
        报警浏览记录,
        道岔动作电流曲线浏览记录
    }
}
